import Vue from 'vue'
// 数据转化
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const util = {
  /**
   * 判断合法对象
   * 不是一个空对象，且不是未定义对象，且不等于空字符串
   * @return true 合法对象/ false 非法对象
   */
  isLegalObject: function(obj) {
    const x = obj
    if (x !== null && x !== undefined && x !== '') {
      return true
    } else {
      return false
    }
  },

  /**
   * 解析url参数
   * @example ?id=12345&a=b
   * @return Object {id:12345,a:b}
   */
  urlParse: function() {
    const url = window.location.search
    const obj = {}
    const reg = /[?&][^?&]+=[^?&]+/g
    const arr = url.match(reg)
    // ['?id=12345', '&a=b']
    if (arr) {
      arr.forEach((item) => {
        const tempArr = item.substring(1).split('=')
        const key = decodeURIComponent(tempArr[0])
        const val = decodeURIComponent(tempArr[1])
        obj[key] = val
      })
    }
    return obj
  },
  /**
   * import Utils from '@/utils/util'
   * 时间戳 进去 转换出 Y-M-D h:m:s日期格式
   * Utils.formatTime(nowDateDay, 'Y-M-D h:m:s')
   */
  formatTime: function(timeStamp, format) {
    const formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
    const returnArr = []

    const date = new Date(timeStamp)
    returnArr.push(date.getFullYear())
    returnArr.push(formatNumber(date.getMonth() + 1))
    returnArr.push(formatNumber(date.getDate()))

    returnArr.push(formatNumber(date.getHours()))
    returnArr.push(formatNumber(date.getMinutes()))
    returnArr.push(formatNumber(date.getSeconds()))

    for (const i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i])
    }
    return format
  },
  /**
   * import Utils from '@/utils/util'
   * Y-M-D h:m:s日期格式 进去 转换出 时间戳数字   date.getTime() 与 date.valueOf()作用相同
   * Utils.formatTranNumber('2018-6-7 8:02:00')
   */
  formatTranNumber: function(str) {
    let timeStr = str
    timeStr = timeStr.replace(/-/g, ':').replace(' ', ':')
    timeStr = timeStr.split(':')
    const time1 = new Date(timeStr[0], (timeStr[1] - 1), timeStr[2], timeStr[3], timeStr[4], timeStr[5])
    // console.log('timestr', time1)
    const tranDate = (new Date(time1)).getTime()
    return tranDate
  },

  // 星期几
  currentWeek: function() {
    const a = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    const week = new Date().getDay()
    return a[week]
  },

  formatLocation: function(longitude, latitude) {
    if (typeof longitude === 'string' && typeof latitude === 'string') {
      longitude = parseFloat(longitude)
      latitude = parseFloat(latitude)
    }
    longitude = longitude.toFixed(2)
    latitude = latitude.toFixed(2)
    return {
      longitude: longitude.toString().split('.'),
      latitude: latitude.toString().split('.')
    }
  },

  // 验证手机号码
  checkMobile: function(phone) {
    // 19937079577
    const mobileExp = /^(1(([3456879][0-9])|(4[57])|(77)))\d{8}$/
    // const mobileExp = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$/
    // const new_m = '13049352355'
    // console.log('mobileExp.test(phone)', new_m, mobileExp.test(new_m))
    return phone && mobileExp.test(phone)
  },
  // 验证中文姓名
  checkRealName: function(name) {
    // console.info('name:%s',name)
    const reg1 = /^[\u4E00-\uFA29\uE7C7-\uE7F3]{2,10}$/
    const reg2 = /^[\u4E00-\uFA29\uE7C7-\uE7F3]{2,10}[·●\\s\\-][\u4E00-\uFA29\uE7C7-\uE7F3]{2,9}$/ // 新疆人姓名,以[·●空格-连]连接
    return name && (reg1.test(name) || reg2.test(name))
  },

  // 邮箱
  eMail: function(email) {
    const _email = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
    // 邮箱
    return email && _email.test(email.replace(/\s/g, ''))
  },
  // 密码  6-20 字母数字
  checkPwd: function(pwd) {
    // let _pwd = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/   // /*字母和数字*/
    const _pwd = /^[0-9A-Za-z]{6,20}$/
    // /* 字母或数字*/
    return pwd && _pwd.test(pwd.replace(/\s/g, ''))
  },

  // 银行卡号
  bankCard: function(bankCard) {
    const _mobilePreg = /^\d{16}$|^\d{19}$/
    // /*银行卡号验证*/
    return bankCard && _mobilePreg.test(bankCard.replace(/\s/g, ''))
  },

  // 验证身份证
  checkIdCard: function(certNo) {
    // 开发环境不校验身份证
    const idCardExp = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|[X|x])$/
    console.log('身份证校检certNo', certNo, 'idCardExp', idCardExp.test(certNo), 'certNoDetail', certNoDetail(certNo))
    return idCardExp && idCardExp.test(certNo) && certNoDetail(certNo)
  },

  // 删除左右两端的空格
  trim: function(str) {
    return str.replace(/(^\s*)|(\s*$)/g, '') // 过滤首尾空格为空
  },

  // 车牌号
  isVehicleNumber: function(vehicleNumber) {
    let result = false
    if (vehicleNumber.length === 7) {
      const regPlate = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/
      result = regPlate.test(vehicleNumber)
    }
    return result
  },

  // mock 取url参数
  param2Obj: function(url) {
    const search = url.split('?')[1]
    if (!search) {
      return {}
    }
    return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
  },

  // 生成随机数
  getUUID: function(len) {
    len = len || 6
    len = parseInt(len, 10)
    len = isNaN(len) ? 6 : len
    var seed = '0123456789abcdefghijklmnopqrstubwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ'
    var seedLen = seed.length - 1
    var uuid = ''
    while (len--) {
      uuid += seed[Math.round(Math.random() * seedLen)]
    }
    return uuid
  },

  // 菜单数据组织
  buildMenu: function(array, ckey) {
    const menuData = []
    const indexKeys = Array.isArray(array) ? array.map((e) => { return e.id }) : []
    ckey = ckey || 'parent_id'
    array.forEach(function(e, i) {
      // 一级菜单
      if (!e[ckey] || (e[ckey] === e.id)) {
        delete e[ckey]
        menuData.push(deepcopy(e)) // 深拷贝
      } else if (Array.isArray(indexKeys)) {
        // 检测ckey有效性
        const parentIndex = indexKeys.findIndex(function(id) {
          return id === e[ckey]
        })
        if (parentIndex === -1) {
          menuData.push(e)
        }
      }
    })
    const findChildren = function(parentArr) {
      if (Array.isArray(parentArr) && parentArr.length) {
        parentArr.forEach(function(parentNode) {
          array.forEach(function(node) {
            if (parentNode.id === node[ckey]) {
              if (parentNode.children) {
                parentNode.children.push(node)
              } else {
                parentNode.children = [node]
              }
            }
          })
          if (parentNode.children) {
            findChildren(parentNode.children)
          }
        })
      }
    }
    findChildren(menuData)
    return menuData
  },

  // 日期格式化
  dateFormat: function(source, ignore_minute) {
    var myDate
    var separate = '-'
    var minute = ''
    if (source === void (0)) {
      source = new Date()
    }
    if (source) {
      if (source.split) {
        source = source.replace(/\-/g, '/')
      } else if (isNaN(parseInt(source))) {
        source = source.toString().replace(/\-/g, '/')
      } else {
        source = new Date(source)
      }

      if (new Date(source) && (new Date(source)).getDate) {
        myDate = new Date(source)
        if (!ignore_minute) {
          minute = (myDate.getHours() < 10 ? ' 0' : ' ') + myDate.getHours() + ':' + (myDate.getMinutes() < 10 ? '0' : '') + myDate.getMinutes()
        }
        return myDate.getFullYear() + separate + (myDate.getMonth() + 1) + separate + (myDate.getDate() < 10 ? '0' : '') + myDate.getDate() + minute
      } else {
        return source.slice(0, 16)
      }
    } else {
      return source
    }
  },

  // ajax错误处理
  catchError: function(error) {
    if (error.response) {
      switch (error.response.status) {
        case 400:
          Vue.prototype.$message({
            message: error.response.data.message || '请求参数异常',
            type: 'error'
          })
          break
        case 401:
          sessionStorage.removeItem('user')
          Vue.prototype.$message({
            message: error.response.data.message || '密码错误或账号不存在！',
            type: 'warning',
            onClose: function() {
              location.reload()
            }
          })
          break
        case 403:
          Vue.prototype.$message({
            message: error.response.data.message || '无访问权限，请联系企业管理员',
            type: 'warning'
          })
          break
        default:
          Vue.prototype.$message({
            message: error.response.data.message || '服务端异常，请联系技术支持',
            type: 'error'
          })
      }
    }
    return Promise.reject(error)
  },

  myConcat: function(arr1, arr2) {
    // 不要直接使用var arr = arr1，这样arr只是arr1的一个引用，两者的修改会互相影响
    var arr = arr1.concat()
    // 或者使用slice()复制，var arr = arr1.slice(0)
    for (let i = 0; i < arr2.length; i++) {
      arr.indexOf(arr2[i]) === -1 ? arr.push(arr2[i]) : 0
    }
    return arr
  },

  // 检查当前要进入的 路由name名，是否有在当前 用户权限路由列表内
  isHavePathName: function(arr, val) {
    const res_val = val
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i]
      if (item.name === res_val) {
        console.log('有isHavePathName')
        return true
      }
    }
    return false
  },

  // 查找匹配的路由
  matchPath: function(router, path) {
    let isMatched = false
    var replayResult = []
    findRoutePath(replayResult, router)
    if (Array.isArray(replayResult) && replayResult.length >= 0) {
      if (replayResult.some(v => v === path)) {
        isMatched = true
      }
    }
    return isMatched
  },

  /*
  * 纳税人识别号验证
  * 15位包括地区编码6位+组织机构代码9位
  */
  checkTaxpayerId: function(taxpayerId) {
    if (taxpayerId !== '' && taxpayerId.length === 15) {
      var addressCode = taxpayerId.substring(0, 6)
      // 校验地址码
      var check = checkAddressCode(addressCode)
      if (!check) {
        return false
      }
      // 校验组织机构代码
      var orgCode = taxpayerId.substring(6, 9)
      check = isValidOrgCode(orgCode)
      if (!check) {
        return false
      }
      return true
    } else {
      return false
    }
  },

  // 18位统一社会信用编码校验
  CheckSocialCreditCodeOrg: function(Code) {
    const patrn = /^[0-9A-Z]+$/
    // 18位校验及大写校验
    if ((Code.length !== 18) || (patrn.test(Code) === false)) {
      return false
    } else {
      let Ancode// 信用代码/税号的每一个值
      let Ancodevalue// 信用代码/税号每一个值的权重
      let total = 0
      const weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28] // 加权因子
      const str = '0123456789ABCDEFGHJKLMNPQRTUWXY'
      // 不用I、O、S、V、Z
      for (let i = 0; i < Code.length - 1; i++) {
        Ancode = Code.substring(i, i + 1)
        Ancodevalue = str.indexOf(Ancode)
        total = total + Ancodevalue * weightedfactors[i]
        // 权重与加权因子相乘之和
      }
      let logiccheckcode = 31 - total % 31
      if (logiccheckcode === 31) {
        logiccheckcode = 0
      }
      const Str = '0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y'
      const Array_Str = Str.split(',')
      logiccheckcode = Array_Str[logiccheckcode]
      const checkcode = Code.substring(17, 18)
      if (logiccheckcode !== checkcode) {
        return false
        // alert("不是有效的统一社会信用编码！");
      } else {
        return true
      }
    }
  },
  /**
   * 将以base64的图片url数据转换为Blob
   * @param urlData
   * 用url方式表示的base64图片数据
   */
  convertBase64UrlToBlob: function(urlData) {
    const arr = urlData.split(',')
    const mime = arr[0].match(/:(.*?);/)[1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
  }

}

export default util

/** 身份证详细验证* */
function certNoDetail(input) {
  const IS_IDCARD = false
  if (input.length === 18) {
    const reg = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([\d|x|X]{1})$/
    if (!reg.test(input)) {
      return IS_IDCARD
    }
  }
  var monthPerDays = [31, 28, 31, 30, 31, 30, 31, 31, 30,
    31, 30, 31
  ]
  var certid = input.toLowerCase()
  var birthDate = certid.length === 15 ? '19' +
    certid.substring(6, 12) : certid.substring(6, 14)
  var year = birthDate.substring(0, 4)
  var month = null
  var day = null
  if (birthDate.substring(4, 5) === '0') {
    month = birthDate.substring(5, 6)
  } else {
    month = birthDate.substring(4, 6)
  }
  if (birthDate.substring(6, 7) === '0') {
    day = birthDate.substring(7, 8)
  } else {
    day = birthDate.substring(6, 8)
  }
  var dd = parseInt(day, 10)
  var mm = parseInt(month, 10)
  var yy = parseInt(year, 10)
  if (mm > 12 || mm < 1 || dd > 31 || dd < 1) {
    return IS_IDCARD
  }
  if (yy % 100 !== 0) {
    if (yy % 4 === 0) {
      monthPerDays[1] = 29
    }
  } else {
    if (yy % 400 === 0) {
      monthPerDays[1] = 29
    }
  }
  if (monthPerDays[mm - 1] < dd) {
    return IS_IDCARD
  }
  if (certid.length === 15) {
    return true
  }
  var arTemp = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5,
    8, 4, 2
  ]
  var num = 0
  var proof = ''
  for (var i = 0; i < 17; i++) {
    num = num + parseInt(certid.substring(i, i + 1), 10) *
      arTemp[i]
  }
  num = num % 11
  switch (num) {
    case 0:
      proof = '1'
      break
    case 1:
      proof = '0'
      break
    case 2:
      proof = 'x'
      break
    case 3:
      proof = '9'
      break
    case 4:
      proof = '8'
      break
    case 5:
      proof = '7'
      break
    case 6:
      proof = '6'
      break
    case 7:
      proof = '5'
      break
    case 8:
      proof = '4'
      break
    case 9:
      proof = '3'
      break
    case 10:
      proof = '2'
      break
  }
  if (proof === '' || !(certid.substring(17, 18) === proof)) {
    return IS_IDCARD
  } else {
    return true
  }
}

// 深拷贝
export function deepcopy(source) {
  if (!source) {
    return source
  }
  const sourceCopy = source instanceof Array ? [] : {}
  for (const item in source) {
    sourceCopy[item] = typeof source[item] === 'object' ? deepcopy(source[item]) : source[item]
  }
  return sourceCopy
}


function findRoutePath(replayResult, array, base) {
  console.log('replayResult', 'array', array, 'base', base)
  array.forEach(function(route) {
    let pathKey = (base || '') + route.path
    replayResult.push(pathKey)
    if (Array.isArray(route.children)) {
      pathKey = route.path + (base || '/')
      findRoutePath(replayResult, route.children, pathKey)
    }
  })
}

/**
*验证组织机构代码是否合法：组织机构代码为8位数字或者拉丁字母+1位校验码。
*验证最后那位校验码是否与根据公式计算的结果相符。
*/
function isValidOrgCode(value) {
  if (value !== '') {
    const part1 = value.substring(0, 8)
    const part2 = value.substring(value.length - 1, 1)
    const ws = [3, 7, 9, 10, 5, 8, 4, 2]
    const str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    const reg = /^([0-9A-Z]){8}$/
    if (!reg.test(part1)) {
      return true
    }
    let sum = 0
    for (let i = 0; i < 8; i++) {
      sum += str.indexOf(part1.charAt(i)) * ws[i]
    }
    let C9 = 11 - (sum % 11)
    const YC9 = part2 + ''
    if (C9 === 11) {
      C9 = '0'
    } else if (C9 === 10) {
      C9 = 'X'
    } else {
      C9 = C9 + ''
    }
    return YC9 !== C9
  }
}

/*
*校验地址码
*/
function checkAddressCode(addressCode) {
  const provinceAndCitys = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江',
    31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南', 44: '广东',
    45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏',
    65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外' }
  const check = /^[1-9]\d{5}$/.test(addressCode)
  if (!check) return false
  if (provinceAndCitys[parseInt(addressCode.substring(0, 2))]) {
    return true
  } else {
    return false
  }
}
